package dfs;

import java.util.ArrayList;
import java.util.LinkedList;
import java.util.List;
import java.util.Queue;

/**
 * 给你一棵二叉树的根节点 root ，请你返回 层数最深的叶子节点的和
 * 输入：root = [1,2,3,4,5,null,6,7,null,null,null,null,8]
 * 输出：15
 * @author le
 */
public class DeepestLeavesSum
{
    public static void main(String[] args)
    {

    }

    /**
     * 广搜
     * @param root 传入的根节点
     * @return
     */
    public int deepestLeavesSum(TreeNode root) {
        Queue<TreeNode> queue = new LinkedList<>();
        if (root != null){
            queue.add(root);
        }
        List<List<Integer>> res = new ArrayList<>();
        while(!queue.isEmpty()){
            int size = queue.size();
            List<Integer> tmp = new ArrayList<>();
            while(size-- > 0){
                TreeNode node = queue.poll();
                tmp.add(node.val);
                if (node.left != null){
                    queue.offer(node.left);
                }
                if (node.right != null){
                    queue.offer(node.right);
                }
            }
            res.add(tmp);
        }
        int sum = 0;
        for (int i = 0;i < res.get(res.size()-1).size();i++){
            sum += res.get(res.size()-1).get(i);
        }
        return sum;
    }
}
